const Koa = require("koa")
const Router = require("koa-router")
const { koaBody } = require("koa-body")

const app = new Koa()
const router = new Router()

// 假设这个 todoList 是从数据库中获取的
let todoList = [
    { id:1, title:'学习' },
    { id:2, title:'吃饭' },
    { id:3, title:'敲代码' }
]

// 获取todoList
router.get('/api/todoList',(ctx,next) => {
    ctx.body = { data: { todoList } , state:1 }
})

// 添加todo
router.post('/api/addTodo',(ctx,next) => {
    const newTodo = {
        id:crypto.randomUUID(),
        title:ctx.request.body.title
    }
    todoList.push(newTodo)
    ctx.body = { data:{ todo:newTodo }, state:1 }
})

// 删除todo
router.post('/api/removeTodo',(ctx,next) => {
    const { id } = ctx.request.body
    todoList = todoList.filter((todo) => todo.id !== id)
    ctx.body = { data:{ id }, state:1 }
})


app.use(koaBody()) // 解析 POST 请求报文
app.use(router.routes()) // 启动路由

// 启动服务器
app.listen(6000,() => {
    console.log('Server is running on http://localhost:6000');
})








